package com.teamtgv.shareshark.task;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.teamtgv.shareshark.AppData;
import com.teamtgv.shareshark.AskActivity;
import com.teamtgv.shareshark.JSONParser;
import com.teamtgv.shareshark.result.Result;

public class AskRecommendationsTask extends AsyncTask<String, String, ArrayList<Result>>{

	public static final String LOG_TAG = AskRecommendationsTask.class.getSimpleName();
	private AskActivity activity;
	private ProgressDialog pDialog;
	
	public AskRecommendationsTask(AskActivity activity) {
		this.activity = activity;
	}
	
    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(activity);
        pDialog.setMessage("Retrieving results...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
	
	@Override
	protected ArrayList<Result> doInBackground(String... args) {
		
		String what = args[0];
		String where = args[1];
		
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("what", what));
        params.add(new BasicNameValuePair("where", where));

        Log.v(LOG_TAG, "Retrieving db results for (" + what + "," + where + ")");
        
        JSONParser jsonParser = new JSONParser();
        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(AppData.FULL_HOST + "get_recommendation.php",
                "GET", params);

        if (json == null) {
        	Log.v(LOG_TAG, "JSON object from HTTP request is null");
        	return null;
        }
        
        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt("success");

            if (success == 1) {
                // successfully created product
            	Log.v(LOG_TAG, "Request successful");
            	
            	ArrayList<Result> resultList = new ArrayList<Result>();

            	 // products found
                // Getting Array of Products
                JSONArray recommendations = json.getJSONArray("recommendations");

                // looping through All Products
                for (int i = 0; i < recommendations.length(); i++) {
                    JSONObject recommendation = recommendations.getJSONObject(i);

                    // Storing each json item in variable
                    int id = recommendation.getInt("id");
                    BigInteger recommenderFacebookId = new BigInteger(recommendation.getString("by"));
                    String whatResult = recommendation.getString("what");
                    String whereResult = recommendation.getString("where");
                    BigInteger targetFacebookId = new BigInteger(recommendation.getString("to"));
                    String dateResult = recommendation.getString("date");
                    int ratingPlusResult = recommendation.getInt("rating_plus");
                    int ratingMinResult = recommendation.getInt("rating_min");
                    String imageUrlResult = recommendation.getString("imageUrl");

                    
                    
                    Result result = new Result(id, recommenderFacebookId, targetFacebookId, whatResult, whereResult, dateResult, ratingPlusResult, ratingMinResult, imageUrlResult);
                    resultList.add(result);

                }
                // closing this screen
                return resultList;
            } else {
                // failed to create product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
	}
	
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(ArrayList<Result> result) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }
	
}
